package com.hfxt.j96springboot.web.shiro;



import com.hfxt.j96springboot.entity.TbRole;
import com.hfxt.j96springboot.entity.TbUser;
import com.hfxt.j96springboot.service.TbRoleService;
import com.hfxt.j96springboot.service.TbUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;
import java.util.List;


//用户自定义的reaml
public class UserRealm extends AuthorizingRealm {


    @Resource
    protected TbUserService tbUserService;

    @Resource
    protected TbRoleService tbRoleService;

    //授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        //认证对象获取
        TbUser tbUser=(TbUser) SecurityUtils.getSubject().getPrincipal();
        //获取该对象的角色
        List<TbRole>  roles=tbRoleService.getRolesByUserid(tbUser.getId());
        for(TbRole tbRole:roles){
            info.addRole(tbRole.getRoleCode());
        }
        return info;
    }


    //认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        //得到认证的用户名
        String username=(String)token.getPrincipal();
        //得到认证的密 码
        String password=new String((char[])token.getCredentials());

        //对象
        TbUser tbUser=null;

        try{
            tbUser=tbUserService.getUserByUsername(username);
        }catch (Exception e){
            e.printStackTrace();
        }

        if(tbUser==null){
            throw new UnknownAccountException();
        }

        //先把用户输入的123转为密文
        String pwd=new Md5Hash(password,tbUser.getSalt(),1024).toString();
        System.out.println(pwd);

        if(!tbUser.getPassword().equals(pwd)){
            throw new IncorrectCredentialsException();
        }

        //封装返回的认证对象
        //第一个参数  是认证的信息
        //第二个参数 是mima
        //第三个参数（密码加密  盐值）  省略
        //第四个参数 是当前realm的名字
        ByteSource salt=ByteSource.Util.bytes(tbUser.getSalt());
        SimpleAuthenticationInfo info=
                new SimpleAuthenticationInfo(tbUser,tbUser.getPassword(),salt,getName());
        return info;
    }
}
